package io.dddplus.common.model;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

import java.io.Serializable;

@Data
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private int code;

    private String msg;

    private T data;

    public static <T> R<T> ok() {
        return restResult(null, RE.OK);
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, RE.OK);
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, RE.OK.getCode(), msg);
    }

    public static <T> R<T> failed() {
        return restResult(null, RE.FAILED);
    }

    public static <T> R<T> failed(String msg) {
        return restResult(null, RE.FAILED.getCode(), msg);
    }

    public static <T> R<T> failed(int code, String msg) {
        return restResult(null, code, msg);
    }

    public static <T> R<T> failed(RE re) {
        return restResult(null, re);
    }

    private static <T> R<T> restResult(T data, RE re) {
        R<T> result = new R<>();
        result.setCode(re.getCode());
        result.setData(data);
        result.setMsg(re.getMsg());
        return result;
    }

    private static <T> R<T> restResult(T data, int code, String msg) {
        R<T> result = new R<>();
        result.setCode(code);
        result.setData(data);
        result.setMsg(msg);
        return result;
    }
}